package com.lg.db.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lg.common.utils.StringUtil;
import com.lg.common.utils.ValidateUtil;
import com.lg.db.mapper.IBaseMapper;
import com.lg.db.model.EmptyModel;
import com.lg.db.page.PageRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基础服务
 *
 * @param <M>
 * @param <T>
 */
public class BaseService<M extends IBaseMapper<T>, T extends EmptyModel> extends ServiceImpl<M, T> {
    // 排序规则： descend 降序
    public static final String ORDER_DESC = "descend";
    // 排序规则： ascend 升序
    public static final String ORDER_ASC = "ascend";

    @Autowired
    protected M ibaseMapper;

    /**
     * 自定义分页查询，需要定义SQL ，XML中statement id 固定为selectPageQuery
     *
     * @param pageRequest
     * @return
     */
    public IPage<T> pageQuery(PageRequest pageRequest) {
        Page<T> page = new Page<>(pageRequest.getCurrent(), pageRequest.getSize());

        if (pageRequest.getSortField() != null && !pageRequest.getSortField().equals("undefined")) {
            //设置排序字段
            List<OrderItem> orders = new ArrayList<>();
            OrderItem orderItem = new OrderItem();
            String field = null;
            //驼峰转下划线
            field = StringUtil.underscoreName(pageRequest.getSortField());
            orderItem.setColumn(field);
            //设置顺序或倒序
            if (StringUtils.equals(pageRequest.getSortOrder(), ORDER_DESC)) {
                orderItem.setAsc(false);
            } else {
                orderItem.setAsc(true);
            }
            orders.add(orderItem);
            page.setOrders(orders);
        }
        Map params = pageRequest.getParams();
        if (params == null) {
            params = new HashMap();
        } else {
            if (params.get("keyword") != null) {
                if (params.get("keyword") instanceof String) {

                    String keyword = params.get("keyword").toString();
                    if (StringUtils.isNotEmpty(keyword)) {
                        if (!ValidateUtil.checkTextDataForNORMAL(keyword)) {
                            return null;
                        }
                    }
                }
            }
        }
        IPage<T> result = ibaseMapper.selectPageQuery(page, params);

        return result;
    }
}
